package com.yc.hwc.web;

import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.servlet.ModelAndView;

import com.yc.hwc.bean.Result;
import com.yc.hwc.bean.User;
import com.yc.hwc.biz.BizException;
import com.yc.hwc.dao.IUserExDao;
import com.yc.util.Utils;

@RestController
@RequestMapping(path = { "hwcuser", "user", "/" })
public class UserDo extends BaseAction<User> {

	// @PostMapping("login")
	public Result<?> login(@RequestBody @Valid User user, Errors errors, HttpSession session) {
		if (errors.hasFieldErrors("account") || errors.hasFieldErrors("pwd")) {
			return Result.failure("登录信息填写不全", errors.getFieldErrors());
		}
		try {
			User dbUser = ((IUserExDao) biz.getDao()).findForLogin(user);
			if (dbUser != null) {
				session.setAttribute("loginedUser", dbUser);
				return Result.success("登录成功！", dbUser);
			}
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		return Result.failure("用户名或密码错误！请尝试使用姓名、邮箱、电话登录！");
	}

	@GetMapping("myinfo")
	public Map<?, ?> myinfo(@SessionAttribute(required = false) User loginedUser) {
		return Utils.asMap(loginedUser, "pwd");
	}

	@GetMapping("changeCls")
	public Result<?> changeCls(@SessionAttribute(required = false) User loginedUser, String clsSn) {
		if (clsSn != null && clsSn.trim().isEmpty() == false) {
			loginedUser.setClsSn(clsSn);
			this.getDao().saveAndFlush(loginedUser);
			return Result.success("clsSn changed: " + clsSn);
		} else {
			return Result.failure("clsSn not change!");
		}
	}

	@PostMapping(path = "saveInfo")
	public Result<?> save(@Valid User e, Errors es, @SessionAttribute User loginedUser) {
		User newUser = new User();
		BeanUtils.copyProperties(loginedUser, newUser);
		Utils.setBean(newUser, "account", e.getAccount(), "email", e.getEmail(), "head", e.getHead());
		Result<?> ret = super.save(newUser, es);
		if (ret.getCode() == 1) {
			BeanUtils.copyProperties(newUser, loginedUser);
		}
		return ret;
	}

	@GetMapping("mylist")
	public ModelAndView mylist(@RequestParam(name = "id", required = false) Long id, @SessionAttribute(required = false) User loginedUser,
			ModelAndView mav) {
		User user = id != null ? biz.get(id) : loginedUser;
		mav.addObject("user", user).setViewName("mylist");
		return mav;
	}

	@Value("${zuul.host}")
	private String host;
	@Value("${zuul.post}")
	private Integer post;

	@GetMapping("forget")
	public Result<?> forget(@Valid User e, Errors es, HttpSession session) {
		if (es.hasFieldErrors("account")) {
			return Result.failure("请正确填写账号或邮箱地址！");
		}
		User user;
		try {
			user = ((IUserExDao) biz.getDao()).getByAccountOrEmail(e.getAccount(), e.getAccount());
			if (user.getEmail() == null || user.getEmail().trim().isEmpty()) {
				return Result.failure("该账号未设置过邮箱地址，无法重置密码！");
			}
		} catch (RuntimeException ex) {
			ex.printStackTrace();
			return Result.failure("账号或邮箱地址错误！");
		}
		ServletContext sc = session.getServletContext();
		String token = "" + new Date().getTime();
		sc.setAttribute(token, user.getId());
		String html = "点击下面的链接完成密码重置功能，重置后的密码是“123456”，重置后请立即登录并修改初始密码！\r\n"
				+ "http://%s:%d/initpwd?t=%s";
		html = String.format(html, host, post, token);
		try {
			sendSimpleMail(user.getEmail(), "廖老师的作业论坛密码重置", html);
		} catch (RuntimeException ex) {
			ex.printStackTrace();
			return Result.failure("邮件发送失败，请联系廖老师！");
		}

		return Result.success("重置密码邮件发送成功！请接收邮件完成密码重置！");
	}

	@GetMapping("initpwd")
	public ModelAndView initpwd(String t, HttpSession session, ModelAndView mav) {
		mav.setViewName("forget");
		Long id = (Long) session.getServletContext().getAttribute(t);
		if (id == null) {
			mav.addObject("result", Result.failure("重置密码操作超时，请重新操作一次！"));
		} else {
			User user = biz.get(id);
			user.setPwd("123456");
			try {
				biz.save(user, null);
				mav.addObject("result", Result.success("密码重置成功！"));
				session.getServletContext().removeAttribute(t);
				mav.setViewName("redirect:to_login?m=1");
			} catch (BizException e) {
				mav.addObject("result", Result.failure(e.getMessage()));
			}
		}
		return mav;
	}

	@Resource
	private JavaMailSender mailSender;

	public void sendSimpleMail(String to, String subject, String content) {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom("306529917@qq.com");
		message.setTo(to);
		message.setSubject(subject);
		message.setText(content);
		mailSender.send(message);
	}

}
